package com.drinks.yiniang.ui.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.banner.BannerRecyclerAdapter;
import com.drinks.yiniang.adapter.home.HomeGridMenuAdapter;
import com.drinks.yiniang.adapter.home.HomePageAdapter;
import com.drinks.yiniang.common.listener.OnHomePageApiRequestListener;
import com.drinks.yiniang.common.recycler.decoration.HomeGoodsItemDecoration;
import com.drinks.yiniang.common.listener.OnHomeNavigationBarClickListener;
import com.drinks.yiniang.entity.comment.BannerEntity;
import com.drinks.yiniang.entity.goods.HomeDataJson;
import com.drinks.yiniang.entity.goods.HomeGoodsJson;
import com.drinks.yiniang.io.api.GoodsApiIO;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.ui.activity.category.CategoryActivity;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.widget.nav.NavigationHomeBarLayout;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnRecyclerItemClickListener;
import com.hansen.library.ui.fragment.BaseFragment;
import com.hansen.library.ui.widget.banner.BannerConfig;
import com.hansen.library.ui.widget.banner.recycler.RecyclerBannerLayout;
import com.hansen.library.ui.widget.image.RatioRoundImageView;
import com.hansen.library.utils.ColorUtils;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.ScreenSizeUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static com.drinks.yiniang.entity.goods.HomeGoodsJson.ITEM_TYPE_HOME_AD_LIST;
import static com.drinks.yiniang.entity.goods.HomeGoodsJson.ITEM_TYPE_HOME_GOODS_LIST;

/**
 * 首页
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class HomePageFragment extends BaseFragment implements OnHomeNavigationBarClickListener, SwipeRefreshLayout.OnRefreshListener,
        AppBarLayout.OnOffsetChangedListener, TabLayout.OnTabSelectedListener, BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, OnRecyclerItemClickListener {

    //nav bar
    private NavigationHomeBarLayout nav_bar_home_page;
    private MSwipeRefreshLayout swipe_refresh_home;
    private AppBarLayout app_bar_home_page;
    //banner
    private RecyclerBannerLayout banner_home;
    private TabLayout tab_home_goods_classify;
    private TabLayout tab_home_goods_sub_classify;
    //recycler
    private BaseRecyclerView rcv_home_page;

    //header view
    //广告
    private RatioRoundImageView iv_home_horizontal_ad;
    private RatioRoundImageView iv_home_vertical_top_ad;
    private RatioRoundImageView iv_home_vertical_bottom_ad;
    //grid menu
    private BaseRecyclerView rcv_home_grid_menu;

    private HomePageAdapter mHomePageAdapter;
    //grid menu
    private HomeGridMenuAdapter mGridMenuAdapter;
    //banner adapter
    private BannerRecyclerAdapter mBannerAdapter;

    //tab list
    private List<HomeDataJson.HomeGoodsAttrs> mTabList;
    private List<HomeDataJson.HomeGoodsSubAttrs> mTabSubList;

    //three banner
    private List<BannerEntity> mThreeBannerList;

    private HomeDataJson.HomeGoodsSubAttrs mAllGoodsAttrs;

    private OnHomeNavigationBarClickListener onHomeNavgationBarClickListener;
    private OnHomePageApiRequestListener onHomePageApiRequestListener;

    private int mAppBarTotalScrollRange;
    private int mPage;

    //选择的属性id
    private String mSelectedAttrsId;
    //选择的子分类id
    private String mSelectedSubCategoryId;

    public HomePageFragment() {
        // Required empty public constructor
    }

    public static HomePageFragment newInstance() {
        return new HomePageFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            onHomeNavgationBarClickListener = (OnHomeNavigationBarClickListener) context;
            onHomePageApiRequestListener = (OnHomePageApiRequestListener) context;
        } catch (ClassCastException e) {
            LogUtils.e(context.toString() + " must implement OnHomeNavigationBarClickListener and OnHomePageApiRequestListener");
        }
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_home_page;
    }

    @Override
    protected void initView(View mView) {
        nav_bar_home_page = mView.findViewById(R.id.nav_bar_home_page);

        swipe_refresh_home = mView.findViewById(R.id.swipe_refresh_home);

        app_bar_home_page = mView.findViewById(R.id.app_bar_home_page);

        banner_home = mView.findViewById(R.id.banner_home);

        tab_home_goods_classify = mView.findViewById(R.id.tab_home_goods_classify);
        tab_home_goods_sub_classify = mView.findViewById(R.id.tab_home_goods_sub_classify);

        rcv_home_page = mView.findViewById(R.id.rcv_home_page);

        //header
        iv_home_horizontal_ad = mView.findViewById(R.id.iv_home_horizontal_ad);
        iv_home_vertical_top_ad = mView.findViewById(R.id.iv_home_vertical_top_ad);
        iv_home_vertical_bottom_ad = mView.findViewById(R.id.iv_home_vertical_bottom_ad);

        rcv_home_grid_menu = mView.findViewById(R.id.rcv_home_grid_menu);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        mAllGoodsAttrs = new HomeDataJson.HomeGoodsSubAttrs();
        mAllGoodsAttrs.setId("0");
        mAllGoodsAttrs.setName(getString(R.string.text_all));

        initBanner();
        initAdapter();
        initGridMenu();
        getHomeData();
    }

    private void initAdapter() {
        app_bar_home_page.post(new Runnable() {
            @Override
            public void run() {
                mAppBarTotalScrollRange = app_bar_home_page.getTotalScrollRange() / 2;
            }
        });

        rcv_home_page.setLayoutManager(RecyclerUtils.getVerticalGridLayout(mContext, 2));
        rcv_home_page.addItemDecoration(HomeGoodsItemDecoration.getItemDPDecoration(10));

        mHomePageAdapter = new HomePageAdapter(mContext, new ArrayList<HomeGoodsJson.HomeGoodsList>());
        mHomePageAdapter.setCommonEmpty(getLayoutInflater(), rcv_home_page);
        mHomePageAdapter.bindToRecyclerView(rcv_home_page);
    }

    //初始化grid menu
    private void initGridMenu() {
        // 设置布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 5);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        rcv_home_grid_menu.setNestedScrollingEnabled(false);
        rcv_home_grid_menu.setLayoutManager(gridLayoutManager);
        rcv_home_grid_menu.addItemDecoration(HomeGoodsItemDecoration.getItemDPDecoration(10));

        mGridMenuAdapter = new HomeGridMenuAdapter(mContext, new ArrayList<HomeDataJson.HomeGoodsCategory>());
        mGridMenuAdapter.bindToRecyclerView(rcv_home_grid_menu);

        List<HomeDataJson.HomeGoodsCategory> lsGrid = new ArrayList<>();

        for(int i = 0; i < 10; i++) {
            lsGrid.add(new HomeDataJson.HomeGoodsCategory());
        }

        mGridMenuAdapter.addData(lsGrid);
    }

    private void initBanner() {
        mBannerAdapter = new BannerRecyclerAdapter(mContext);
        mBannerAdapter.setOnItemClickListener(this);

        banner_home.setAutoPlay(true)
                .setLoop(true)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setBannerAdapter(mBannerAdapter)
                .start();
    }

    @Override
    protected void listener() {
        nav_bar_home_page.setOnNavgationBarClickListener(this);

        swipe_refresh_home.setOnRefreshListener(this);

        app_bar_home_page.addOnOffsetChangedListener(this);

        tab_home_goods_classify.addOnTabSelectedListener(this);
        tab_home_goods_sub_classify.addOnTabSelectedListener(this);

        iv_home_horizontal_ad.setOnClickListener(this);
        iv_home_vertical_top_ad.setOnClickListener(this);
        iv_home_vertical_bottom_ad.setOnClickListener(this);

        mGridMenuAdapter.setOnItemClickListener(this);
        mHomePageAdapter.setOnItemClickListener(this);
        mHomePageAdapter.setOnItemChildClickListener(this);
        mHomePageAdapter.setOnLoadMoreListener(this, rcv_home_page);
    }

    @Override
    protected void widgetClick(View v) {
        BannerEntity banner;
        String type, value;

        switch (v.getId()) {
            case R.id.iv_home_horizontal_ad://左边大的广告
                banner = !CommonUtils.isArrayIndexOutOfBounds(mThreeBannerList, 0) ? mThreeBannerList.get(0) : null;
                type = banner != null ? banner.getType() : null;
                value = banner != null ? banner.getValue() : null;
                ActivityUtils.startActivityByAdType(mContext, type, value);
                break;
            case R.id.iv_home_vertical_top_ad://右上边的广告
                banner = !CommonUtils.isArrayIndexOutOfBounds(mThreeBannerList, 1) ? mThreeBannerList.get(1) : null;
                type = banner != null ? banner.getType() : null;
                value = banner != null ? banner.getValue() : null;
                ActivityUtils.startActivityByAdType(mContext, type, value);
                break;
            case R.id.iv_home_vertical_bottom_ad://右下的广告
                banner = !CommonUtils.isArrayIndexOutOfBounds(mThreeBannerList, 2) ? mThreeBannerList.get(2) : null;
                type = banner != null ? banner.getType() : null;
                value = banner != null ? banner.getValue() : null;
                ActivityUtils.startActivityByAdType(mContext, type, value);
                break;
            default:
                break;
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset >= 0) {
            if(!swipe_refresh_home.isEnabled()) swipe_refresh_home.setEnabled(true);
        } else {
            if(swipe_refresh_home.isEnabled()) swipe_refresh_home.setEnabled(false);
        }

        if (mAppBarTotalScrollRange > 0) {
            float fraction = Math.abs(verticalOffset * 1.0f) / mAppBarTotalScrollRange;
            nav_bar_home_page.setBackgroundColor(ColorUtils.changeAlpha(ContextCompat.getColor(mContext, R.color.white), fraction));
            nav_bar_home_page.changeNavBarDrawable(fraction < 0.1);
        }
    }

    @Override
    public void onAddress(View v) {
        if(onHomeNavgationBarClickListener != null) {
            onHomeNavgationBarClickListener.onAddress(v);
        }
    }

    @Override
    public void onSearchClick(View v) {
        if(onHomeNavgationBarClickListener != null) {
            onHomeNavgationBarClickListener.onSearchClick(v);
        }
    }

    @Override
    public void onMessage(View v) {
        if(onHomeNavgationBarClickListener != null) {
            onHomeNavgationBarClickListener.onMessage(v);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(banner_home != null) {
            banner_home.startAutoPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if(banner_home != null) {
            banner_home.stopAutoPlay();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(banner_home != null) {
           if(hidden) banner_home.stopAutoPlay();
           else banner_home.startAutoPlay();
        }
    }

    @Override
    public void onRefresh() {
        getHomeData();
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int pos = tab.getPosition();

        switch (tab.parent.getId()) {
            case R.id.tab_home_goods_classify://分类
                if(CommonUtils.isArrayIndexOutOfBounds(mTabList, pos)) {
                    return;
                }

                mSelectedAttrsId = mTabList.get(pos).getId();

                setTabSubList(mTabList.get(pos).getSub_category());
                break;
            case R.id.tab_home_goods_sub_classify://子分类
                if(CommonUtils.isArrayIndexOutOfBounds(mTabSubList, pos)) {
                    return;
                }

                mSelectedSubCategoryId = mTabSubList.get(pos).getId();

                getHomeGoods();
                break;
            default:
                break;
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent mIntent;

        if(adapter instanceof HomeGridMenuAdapter) {
            HomeDataJson.HomeGoodsCategory data = mGridMenuAdapter.getItem(position);

            if(data == null) {
                return;
            }

            mIntent = new Intent(mContext, CategoryActivity.class);
            mIntent.putExtra(Constants.KeyCategoryId, data.getCategory_id());
            startActivity(mIntent);
        } else {
            HomeGoodsJson.HomeGoodsList data = mHomePageAdapter.getItem(position);

            if(data == null) {
                return;
            }

            switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
                case ITEM_TYPE_HOME_AD_LIST://商品列表穿插的广告
                    ActivityUtils.startActivityByAdType(mContext, data.getType(), data.getValue());
                    break;
                case ITEM_TYPE_HOME_GOODS_LIST://商品
                    mIntent = new Intent(mContext, GoodsDetailsActivity.class);
                    mIntent.putExtra(Constants.KeyGoodsId, data.getId());
                    startActivity(mIntent);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        HomeGoodsJson.HomeGoodsList data = mHomePageAdapter.getItem(position);

        if(data == null) {
            return;
        }

        switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
            case ITEM_TYPE_HOME_GOODS_LIST://商品
                addToCart(data.getId());
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder holder) {
        BannerEntity data = mBannerAdapter.getItem(holder.getAdapterPosition());

        if(data != null) {
            ActivityUtils.startActivityByAdType(mContext, data.getType(), data.getValue());
        }
    }

    private void addToCart(String goodsId) {
        //设置传参object
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        GoodsApiIO.getInstance().getHomeGoodsList(mSelectedAttrsId, mSelectedSubCategoryId, mPage, new APIRequestCallback<HomeGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(HomeGoodsJson res) {
                if(mHomePageAdapter == null) {
                    return;
                }

                mPage++;

                if(res.getData().getData() != null) {
                    mHomePageAdapter.addData(res.getData().getData());
                }


                if(CommonUtils.isHasMoreData(res.getData().getData())) {
                    mHomePageAdapter.loadMoreComplete();
                } else {
                    mHomePageAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                mHomePageAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取首页商品列表
    private void getHomeGoods() {
        if(mHomePageAdapter.getData() != null) {
            mHomePageAdapter.getData().clear();
            mHomePageAdapter.addData(mHomePageAdapter.getData());
        }

        if(StringUtils.isEmpty(mSelectedAttrsId) || StringUtils.isEmpty(mSelectedSubCategoryId)) {
            return;
        }

        mPage = 1;

        GoodsApiIO.getInstance().getHomeGoodsList(mSelectedAttrsId, mSelectedSubCategoryId, mPage, new APIRequestCallback<HomeGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(HomeGoodsJson res) {
                if(mHomePageAdapter == null) {
                    return;
                }

                mPage++;

                if(res.getData().getData() != null) {
                    mHomePageAdapter.getData().clear();
                    mHomePageAdapter.addData(res.getData().getData());
                }


                if(CommonUtils.isHasMoreData(res.getData().getData())) {
                    mHomePageAdapter.loadMoreComplete();
                } else {
                    mHomePageAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mHomePageAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取首页数据
    private void getHomeData() {
        if (!swipe_refresh_home.isRefreshing()) {
            showLoadingDialog();
        }

        GoodsApiIO.getInstance().getHomeData(new APIRequestCallback<HomeDataJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(HomeDataJson res) {
                setHomeData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                swipe_refresh_home.setRefreshing(false);
                dismissDialog();

                if(onHomePageApiRequestListener != null) {//第一次回调给main activity
                    onHomePageApiRequestListener.OnHomePageApiRequestSuccess();
                    onHomePageApiRequestListener = null;
                }
            }
        });
    }

    private void setHomeData(HomeDataJson.HomeData data) {
        mBannerAdapter.addBannerData(data.getTop_banner());

        banner_home.setBannerAdapter(mBannerAdapter);
        banner_home.update();

        if(data.getCategory() != null) {
            mGridMenuAdapter.getData().clear();
            mGridMenuAdapter.addData(data.getCategory());
        }

        setTabList(data.getAttribute());

        mThreeBannerList = data.getMid_banner();

        if(!CommonUtils.isEmptyList(mThreeBannerList)) {
            GlideUtils.load(mContext, iv_home_horizontal_ad, mThreeBannerList.size() > 0 ? mThreeBannerList.get(0).getCover_url() : "");
            GlideUtils.load(mContext, iv_home_vertical_top_ad, mThreeBannerList.size() > 1 ? mThreeBannerList.get(1).getCover_url() : "");
            GlideUtils.load(mContext, iv_home_vertical_bottom_ad, mThreeBannerList.size() > 2 ? mThreeBannerList.get(2).getCover_url() : "");
        }
    }

    private void setTabList(List<HomeDataJson.HomeGoodsAttrs> list) {
        if (mTabList == null) {
            mTabList = new ArrayList<>();
        }

        mTabList.clear();

        tab_home_goods_classify.removeAllTabs();

        if(CommonUtils.isEmptyList(list)) {
            return;
        }

        mTabList.addAll(list);

        for (int i = 0; i < mTabList.size(); i++) {
            tab_home_goods_classify.addTab(tab_home_goods_classify.newTab().setText(mTabList.get(i).getName()));
        }

        if(tab_home_goods_classify.getChildAt(0) instanceof  LinearLayout) {
            LinearLayout linearLayout = (LinearLayout) tab_home_goods_classify.getChildAt(0);
            linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
            //设置分割线的drawable
            linearLayout.setDividerDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_vertical_tablayout));
            //该方法传入的参数为像素的大小，故需要使用dp转px的方法
            linearLayout.setDividerPadding(ScreenSizeUtils.dp2px(mContext, 16));
        }
    }

    private void setTabSubList(List<HomeDataJson.HomeGoodsSubAttrs> subList) {
        if (mTabSubList == null) {
            mTabSubList = new ArrayList<>();
        }

        mTabSubList.clear();
        mTabSubList.add(mAllGoodsAttrs);

        tab_home_goods_sub_classify.removeAllTabs();

        if(!CommonUtils.isEmptyList(subList)) {
            mTabSubList.addAll(subList);
        }

        for (int i = 0; i < mTabSubList.size(); i++) {
            tab_home_goods_sub_classify.addTab(tab_home_goods_sub_classify.newTab().setText(mTabSubList.get(i).getName()));
        }
    }
}
